/**
 * 小说目录页
 */
import { listNovelAllChapterUsingGet } from "@/services/novel-web/chapterController";
import { getNovelInfoUsingGet } from "@/services/novel-web/novelController";
import { MessageError } from "@/utils/commonUtils";
import { PageContainer } from "@ant-design/pro-components";
import { history, useParams } from "@umijs/max";
import { Card, Divider, List, Typography } from "antd";
import { useEffect, useState } from "react";
import styles from "./index.less";
const {Title,Text,Paragraph} = Typography;


const NovelContents : React.FC = () =>{

  // url :id
  const {id:novelId} = useParams<{id: string}>();
  // novel
  const [info,setInfo] = useState<API.NovelInfo>();

  const loadNovelInfo = async (id:string) => {
    try {
      const resp = await getNovelInfoUsingGet({
        id: Number(id),
      });
      setInfo(resp.data);

    } catch (error: any) {
      MessageError(error);
    }
  };
  // chapters
  const [chapters,setChapters] = useState<API.ChapterVO[]>([]);

  const loadChapters = async (id:string)=>{
    try {
      const resp = await listNovelAllChapterUsingGet({
        novelId: Number(id),
      });

      setChapters(resp.data ?? []);

    } catch(error:any) {
      MessageError(error);
    }
  };


  useEffect(()=>{
    if(novelId == '0') {
      history.push("/");
    }
    loadNovelInfo(novelId ?? '');
    loadChapters(novelId ?? '');
  },[])


  // list 
  const handleItemClick = (item?: API.ChapterVO ) =>{
    history.push(`/novel/${novelId}/${item?.id}`);
  }

  return (
    <PageContainer
      header={{
        ghost: true,
        breadcrumb:{
          items: [
            {
              href: '/welcome',
              title: '首页',
            },
            {
              href: `/novel/${novelId}`,
              title: info?.name,
            },
            {
              title: '目录',
            }
          ]
        },
      }}
    ><div>
      <Divider/>
      <Title style={{marginTop: 16, textAlign: 'center'}} level={2}>{info?.name}</Title>
      <Divider/>
      <Card style={{marginTop: 16}}>
        <List
          grid={{gutter: 16,column: 4}}
          dataSource={chapters}
          renderItem={(item: API.ChapterVO) => (
            <div className={styles.item} onClick={()=>handleItemClick(item)}>
              <Text className={styles.text}>
              {item.title}
              </Text>
            </div>
          )}
        />
                
      </Card>

    </div></PageContainer>
  );
};




export default NovelContents;